
package com.e885.util.io;

import java.io.*;

/**
 * <br>
 * Copyright: Copyright (c) 2002-2007<br>
 * Company: E885 有限公司
 * 
 * @author Eric Gau(gau168.gau@msa.hinet.net)
 * @version 1.0
 */
public class StreamCopier
{
	/**
     * 適用在 File
     */
	public static int FILE_BUFFER_SIZE = 1024;

	/**
     * 適用在 Net
     */
	public static int NET_BUFFER_SIZE = 256;

	/**
     * 將 inputstream 的內容, copy 到以 pathName 建立的 FileOutputStream, 使用 buffer 的長度為 1
     * 
     * @param in InputStream
     * @param pathName String
     * @throws IOException
     */
	public static void copy( InputStream in, String pathName ) throws IOException
	{
		if( pathName == null ) { throw new IllegalArgumentException( "pathName is null" ); }

		FileOutputStream fos = new FileOutputStream( new File( pathName ) );

		copy( in, fos );

		fos.close();
	}

	/**
     * 將 inputstream 的內容, copy 到 OutputStream, 使用 buffer 的長度為 1
     * 
     * @param in InputStream
     * @param out OutputStream
     * @throws IOException
     */
	public static void copy( InputStream in, OutputStream out ) throws IOException
	{
		copy( in, out, 1 );
	}

	/**
     * 將 inputstream 的內容, copy 到以 pathName 建立的 FileOutputStream, 使用 buffer 的長度為 bufferSize
     * 
     * @param in InputStream
     * @param pathName String
     * @throws IOException
     */
	public static void copy( InputStream in, String pathName, int bufferSize ) throws IOException
	{
		if( pathName == null ) { throw new IllegalArgumentException( "pathName is null" ); }

		FileOutputStream fos = new FileOutputStream( new File( pathName ) );

		copy( in, fos, bufferSize );

		fos.close();
	}

	/**
     * 將 inputstream 的內容, copy 到 OutputStream, 使用 buffer 的長度為 bufferSize
     * 
     * @param in InputStream
     * @param out OutputStream
     * @param bufferSize int
     * @throws IOException
     */
	public static void copy( InputStream in, OutputStream out, int bufferSize ) throws IOException
	{
		if( in == null ) { throw new IllegalArgumentException( "in is null" ); }

		if( out == null ) { throw new IllegalArgumentException( "out is null" ); }

		synchronized( in )
		{
			synchronized( out )
			{
				byte[] buffer = new byte[ bufferSize ];
				int bytesRead = 0;

				while( ( bytesRead = in.read( buffer, 0, buffer.length ) ) != -1 )
				{
					out.write( buffer, 0, bytesRead );
				}
			}
		}
	}
}
